<template>
  <div class="service-record-container">
    <div class="page-header">
      <h2>服务记录</h2>

    </div>

    <!-- 搜索区域 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="老人姓名">
          <el-select v-model="queryParams.userId" filterable  placeholder="请选择" style="width: 100px" clearable>
            <el-option v-for="item in userList" :key="item.id" :label="item.userName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="服务人员">
          <el-select v-model="queryParams.staffId" filterable  placeholder="请选择" style="width: 100px" clearable>
            <el-option v-for="item in staffList" :key="item.id" :label="item.userName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" v-show="checkUserAuth(1) || checkUserAuth(2)" @click="openDialog()">
            <el-icon><Plus /></el-icon>添加记录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container">
      <el-table :data="recordList" border stripe v-loading="loading">
        <el-table-column prop="startDate" label="服务日期" width="120" />
        <el-table-column prop="userIdName" label="老人姓名" />
        <el-table-column prop="staffIdName" label="工作人员" />
        <el-table-column prop="content" label="服务内容" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="score" label="评分" />
        <el-table-column prop="evaluate" label="评价" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" v-show="checkUserAuth(0)" link @click="openDialog(row)">打分</el-button>
            <el-button type="primary" v-show="checkUserAuth(1) || checkUserAuth(2)" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleRead(row)">查看</el-button>
            <el-button type="danger" v-show="checkUserAuth(2)" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :disabled="dialogType === 'read'"
        label-width="100px"
      >
        <el-form-item label="服务日期" prop="startDate">
          <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              :disabled="dialogType !== 'edit' && dialogType !== 'add'"
              value-format="YYYY-MM-DD"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="老人姓名" prop="userId">
          <el-select :disabled="!!form.id" v-model="form.userId" placeholder="请选择老人信息" style="width: 100%">
            <el-option v-for="item in userList" :label="item.userName" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="员工姓名" prop="staffId">
          <el-select :disabled="!!form.id" v-model="form.staffId" placeholder="请选择员工信息" style="width: 100%">
            <el-option v-for="item in staffList" :label="item.userName" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务内容" prop="content">
          <el-input :disabled="dialogType !== 'edit' && dialogType !== 'add' "
            v-model="form.content"
            type="textarea"
            :rows="3"
            placeholder="请输入服务描述"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :disabled="dialogType !== 'edit' && dialogType !== 'add'"
            :rows="3"
            placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="评分" prop="score" >
          <el-input-number  :disabled="dialogType !== 'evaluate'" type="number" v-model="form.score" placeholder="请打分" label="评分"/>
        </el-form-item>
        <el-form-item label="评价" prop="evaluate">
          <el-input :disabled="dialogType !== 'evaluate'" v-model="form.evaluate" placeholder="请评价"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          确 定
        </el-button>
      </template>
    </el-dialog>

    <!-- 反馈对话框 -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { get, post, put, del } from '@/utils/request'
import type { FormInstance } from 'element-plus'
import type { ServiceRecord } from '@/types/service-record'
import {getUserListByType } from "@/api/user.ts";
import {number} from "echarts";
import {checkUserAuth} from "@/utils/userAuth.ts";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  serviceType: undefined,
  startDates: '',
  endDate: '',
  staffId: null,
  userId: null,
})

// 日期范围
const dateRange = ref<string[]>([])

// 数据列表
const recordList = ref<ServiceRecord[]>([])
const total = ref(0)
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = computed(() => form.id ? '编辑服务记录' : '添加服务记录')
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 反馈对话框相关
const feedbackVisible = ref(false)
const feedbackFormRef = ref<FormInstance>()
const feedbackLoading = ref(false)
const feedbackForm = reactive({
  id: undefined,
  feedback: ''
})
const userList = ref([])
const staffList = ref([])
// 表单对象
const form = reactive<ServiceRecord>({
  id: null,
  userId: null,
  staffId:null,
  content:'',
  startDate: new Date().toISOString().split('T')[0],
  score: 0,
  remark: '',
  evaluate: ''
})

// 表单验证规则
const rules = reactive({
  startDate: [{ required: true, message: '请选择服务日期', trigger: 'change' }],
  userId: [{ required: true, message: '请选择老人信息', trigger: 'change' }],
  staffId: [
    { required: true, message: '请选择工作人员信息',trigger: 'change' },
  ],
  content: [{ required: true, message: '请输入服务内容', trigger: 'blur' }],
  score: [{ required: true, message: '请打分', trigger: 'blur' },
    {type:'number',min: 0,max:10,message: '评分应该是0-10分之间'}]
})

// 状态标签转换方法
const getServiceTypeTag = (val: number) => {
  const map = ['', 'success', 'warning', 'danger', 'info']
  return map[val] || ''
}
const dialogType = ref('')
// 打开对话框
const openDialog = (row?: ServiceRecord) => {
  dialogType.value = 'evaluate'
  dialogValue(row)
}
const dialogValue = (row) =>{
  if (row) {
    Object.assign(form, row)
  } else {
    dialogType.value = 'add'
    resetForm()
    getUserList();
  }
  dialogVisible.value = true
}
const handleEdit = (row: ServiceRecord) => {
  dialogType.value = 'edit'
  dialogValue(row)
}
const handleRead = (row: ServiceRecord) => {
  dialogType.value = 'read'
  dialogValue(row)
}

const getUserList = () => {
  getUserListByType({'userType':1}).then(res=>{
    userList.value = res.records;
  })
  getUserListByType({'userType':2}).then(res=>{
    staffList.value = res.records;
  })
}
// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  form.id = null
  form.userId = undefined
  form.startDates = ''
  form.staffId = null
  form.score = 0
  form.remark = ''
  form.content = ''

}

// 获取服务记录列表
const fetchRecords = async () => {
  try {
    loading.value = true
    const params = {
      ...queryParams,
      startDates: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    }

    const res = await get('/service-records/page', params)
    recordList.value = res.records
    total.value = res.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    submitLoading.value = true

    const api = form.id ? put : post
    const url = form.id ? `/service-records/update` : '/service-records'

    await api(url, form)
    ElMessage.success(form.id ? '更新成功' : '添加成功')
    dialogVisible.value = false
    fetchRecords()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 处理反馈

// 提交反馈
const submitFeedback = async () => {
  if (!feedbackFormRef.value) return
  try {
    await feedbackFormRef.value.validate()
    feedbackLoading.value = true

    await post('/service-record/feedback', feedbackForm)
    ElMessage.success('反馈提交成功')
    feedbackVisible.value = false
    fetchRecords()
  } catch (error) {
    console.error('提交反馈失败:', error)
  } finally {
    feedbackLoading.value = false
  }
}

// 删除记录
const handleDelete = async (row: ServiceRecord) => {
  try {
    await ElMessageBox.confirm('确定删除该记录吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await del(`/service-records/${row.id}`)
    ElMessage.success('删除成功')
    fetchRecords()
  } catch (error) {
    console.log('取消删除')
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchRecords()
}

// 重置查询
const resetQuery = () => {
  dateRange.value = []
  queryParams.serviceType = undefined
  queryParams.startDates = ''
  queryParams.endDate = ''
  queryParams.userId = null
  queryParams.staffId = null
  fetchRecords()
}

// 分页处理
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  fetchRecords()
}

const handleCurrentChange = (num: number) => {
  queryParams.pageNum = num
  fetchRecords()
}

// 初始化加载
onMounted(() => {
  fetchRecords()
  getUserList()
})
</script>

<style scoped>
.service-record-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
